<?php
namespace app\shop\model;
use app\BaseModel;
use app\helppay\model\Helppay;
use app\integral\model\IntegralGoods;
use app\member\model\Integral;
use app\member\model\Member;
use app\member\model\StoredOrder;
use app\shop\controller\IndexShopGoods;
use think\facade\Db;
use app\shop\model\AdminShopOrderGoods;
use app\shop\model\AdminShopOrder;



class AdminShopOrderRefund extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shop_order_refund';
    protected $append = [
        'goods_text',
        'status_text',
        'order_goods_text'
    ];
    /**
     * User: chenniang
     * Date: 2019-09-19 11:17
     * @param $value
     * @param $data
     * @return \think\Collection
     * descption:获取自订单
     */
    public function getOrderGoodsTextAttr($value,$data){
        $order = Db::name('longbing_card_shop_order_item')->where(['order_id'=>$data['order_id']])->select();
        return $order;
    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * 获取器 获取子订单
     */
    public function getGoodsTextAttr($value,$data){
        $orer_goods_model = new AdminShopOrderGoods();
        $dis = ['order_id'=>$data['order_id']];
        return $orer_goods_model->changeInfo($dis);
    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * 获取器 status text
     */
    public function getStatusTextAttr($value,$data){
        if(in_array($data['status'],[1,2,3])){
            $statusArr = [1 => '申请退款中', 2 => '已同意退款', 3 => '已拒绝退款'];
            return $statusArr[$data['status']];
        }
    }

    /**
     * User: chenniang
     * Date: 2019-10-11 14:13
     * @param $value
     * @return void
     * descption:退款价格
     */
    public function getRefundPriceAttr($value){
        return !empty($value)?$value:'';
    }

    /**
     * 获取订单列表
     */
    public function refundList($dis,$page=10){
        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_shop_order b' ,'a.order_id = b.id')
            ->leftJoin('longbing_card_user c' ,'c.id = b.user_id')
            ->leftJoin('longbing_card_user_info d' ,'d.fans_id = b.to_uid')
            ->where($dis)
            ->field(['a.id,a.refund_price,b.stored,a.order_id, a.create_time, a.status, b.user_id, c.nickName, d.name, b.price, b.total_price, b.address, 
b.address_detail, b.transaction_id, b.out_refund_no,b.help_pay'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();
        return $data;
    }

    /**
     * 修改订单
     */

    public function refundUpdate($dis,$data){
        $data['update_time'] = time();
        $res = Db::name($this->name)->where($dis)->update($data);
        return $res;
    }
    /**
     * 获取订单详情
     */
    public function refundInfo($dis){
        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_shop_order b' ,'a.order_id = b.id')
            ->where($dis)
            ->field(['a.id,a.uniacid,a.integral,a.order_id,a.status,b.refund_status,b.user_id,b.to_uid, b.price, b.total_price, b.transaction_id, b.out_trade_no,b.stored,b.help_pay'])
            ->find();
        return !empty($data)?$data->toArray():$data;
    }


    /**
     * User: chenniang
     * Date: 2019-09-09 18:50
     * @return \think\Response
     * descption:同意退款
     */
    public function orderRefundApi($id,$refund_prices=0,$app,$payConfig){

        $order_model = new IndexShopOrder();

        $water_model = new IndexSellingWater();

        $goods_model = new IndexGoods();

        $spe_price_model = new IndexShopSpePrice();

        $count_model = new IndexCardCount();

        $item = $this->refundInfo(['a.id' => $id]);

        if (empty($item)) {

            return ['code'=>500,'msg'=>'not find refundorder'];

        }
        if (empty($item['out_trade_no'])) {

            return ['code'=>500,'msg'=>'not find order'];
        }
        if ( $item[ 'status' ] != 1 || $item[ 'refund_status' ] != 1 ) {

            return ['code'=>500,'msg'=>'status is error'];

        }
        if($refund_prices>$item['total_price']){

            return ['code'=>500,'msg'=>'退款金额大于付款金额'];

        }
        $refund_price = !empty($refund_prices)?$refund_prices:$item['total_price'];

        $response[ 'return_code' ] = 'SUCCESS';

        $response[ 'result_code' ] = 'SUCCESS' ;

        $response[ 'out_refund_no' ] = $item['out_trade_no'];

        if($refund_prices>0){
            //储值退款
            if($item['stored']>0){
                //余额退款
                $stored_order_model = new StoredOrder();
                //增加记录
                $stored_order_model->orderRefundStore($item['order_id'],$app,$refund_prices);

            }else{
                //微信退款
                $response = orderRefundApi($payConfig,$item['total_price'],$refund_price,$item['transaction_id']);

            }

        }

        if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

            $out_refund_no = $response[ 'out_refund_no' ];

            $order_model->orderUpdate(['id' => $item['order_id']],['out_refund_no' => $out_refund_no,'pay_status'=> 2, 'refund_status' => 2]);

            $this->refundUpdate(['id'=> $id],['status'=>2,'refund_price'=>$refund_price]);

            $water_model->refundWater(['order_id'=>$item['order_id'],'waiting'=>1]);
            //会员退款
            $member_model = new Member();

            $member_model->refundOrder($item['order_id']);

            $admin_order_model = new AdminShopOrder();
            //加库存 退销量
            $admin_order_model->refundStock($item['order_id']);

            $is_bargain = $order_model->where(['id'=>$item['order_id']])->value('is_bargain');
            //砍价订单 如果超时需要改变砍价记录的状态
            if($is_bargain==1){

                $bargain_model = new BargainRecord();

                $bargain_model->dataUpdate(['order_id'=>$item['order_id']],['status'=>5]);
            }
            //退还积分
            if($item['integral']>0){

                $i_model = new Integral();

                $i_model->incUserIntegral($item['order_id'],$item['user_id'],$item['uniacid'],5);
            }

            $insertData = array(

                'user_id' => $item['user_id'],

                'to_uid'  => $item['to_uid'],

                'sign'    => 'view',

                'type'    => 24,

                'uniacid' => $item['uniacid'],

                'target'  => $item['order_id']
            );

            $insert_id = $count_model->countAdd($insertData);

            $push_data = array(

                'action'  => 'longbingSendWxServiceNotice',

                'event'   => 'longbingSendWxServiceNotice',

                'count_id'=> $insert_id
            );

            publisher(json_encode($push_data ,true));

            return true;

        }else{

            $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

            return ['code'=>500,'msg'=> $discption];
        }
    }





}